import {Component, OnInit} from '@angular/core';
import {OAuthConfig} from './OAuthConfig';
import {OAuthSession} from './OAuthSession';
import {GnLoginUser, GnMessageService} from 'geminis-ng';
import {Router} from '@angular/router';

@Component({
  selector: 'portal-login',
  template: ``
})
export class LoginComponent implements OnInit {

  constructor(private loginUser: GnLoginUser,
              private oauthConfig: OAuthConfig,
              private messageService: GnMessageService,
              private router: Router,
              private oauthSession: OAuthSession) {
  }

  ngOnInit(): void {
    this.oauthConfig.load()
      .subscribe(config => {
        if (this.loginUser.isLogin) {
          this.messageService.clean();
          const entryUrl = sessionStorage.getItem('blockUrl');
          this.router.navigateByUrl(entryUrl);
          return;
        }
        this.oauthSession.refresh();
        const params = [
          'response_type=' + config.responseType,
          'state=' + this.oauthSession.state,
          'client_id=' + config.clientId,
          'scope=' + config.scope,
          'redirect_uri=' + encodeURIComponent(config.redirectUri)
        ];
        if (this.oauthConfig.usePkce) {
          params.push(
            'code_challenge=' + this.oauthSession.codeChallenge,
            'code_challenge_method=S256'
          );
        }
        window.location.href = config.oidcConfig.authorization_endpoint + '?' + params.join('&');
      });
  }
}
